<template>
  <view class="mine-order-evaluate">
    <view class="header-container">
      <base-nav title="商品评价">
        <view slot="left" class="header-left" @click="leftClick">
          <image src="/static/images/icon/icon_arror_left.png" />
        </view>
      </base-nav>
    </view>
    <view v-if="showResult" class="orderList">
      <view v-for="(item, index) in orderListData" :key="index" class="listItem">
        <view class="item-content">
          <view class="commodity-box">
            <view v-for="(sItem, sIndex) in item.goods_skus" :key="sIndex" class="commodity-item">
              <view class="commodity-image">
                <image :src="sItem.goods_image" />
              </view>
              <view class="commodity-title">
                <view class="title">{{ sItem.goods_name }}</view>
                <view class="sku">{{ sItem.goods_attr }}</view>
              </view>
              <view class="commodity-num">x{{ sItem.goods_num }}</view>
            </view>
          </view>
          <view class="startColumn">
            <view class="rowText" @click="showIem(item)">商品评价</view>
            <view class="rowStart">
              <star :disabled="!can_edit" :source.sync="formData" :name-key="item.goods_id"></star>
            </view>
          </view>
          <view class="comment-box">
            <view class="comment-content">
              <textarea v-model="item.commentContent" :disabled="!can_edit" :maxlength="300" placeholder="从多个角度评价宝贝，可以帮助更多想买的人~" placeholder-style="font-size: 26rpx;color:#B2B2B2"></textarea>
            </view>
            <view class="comment-pic-list">
              <view v-for="(video, videoIndex) in item.commentVideoList" :key="videoIndex" class="pic-item">
                <image v-if="video.video_cover" class="con-img-item" :src="video.video_cover+'?x-oss-process=image/rotate,0'" mode="aspectFill" />
                <!-- <video v-else :controls="false" :show-center-play-btn="false" style="width: 100%; height: 100%" :src="video"></video>
                -->
                <view class="play-button" @click.stop.prevent="playVideo(video)">
                  <image class="icon-play" src="/static/images/order/icon_evaluate_play.png" />
                </view>
                <image v-if="can_edit" class="icon-del" src="/static/images/icon/icon_del.png" @click.stop="delPic(item, videoIndex, 'commentVideoList')" />
              </view>
              <view v-for="(pic, picIndex) in item.commentImgList" :key="pic" class="pic-item">
                <image class="con-img-item" :src="pic+'?x-oss-process=image/rotate,0'" mode="aspectFill" @click="showPreviewImg(item.commentImgList, picIndex, 2)" />
                <image v-if="can_edit" class="icon-del" src="/static/images/icon/icon_del.png" @click.stop="delPic(item, picIndex, 'commentImgList')" />
              </view>
              <view v-if="can_edit" class="pic-item" @click="showPopup(item)">
                <image src="/static/images/order/icon_evaluate_up.png" />
                <image v-if="index === 0 && showLimit" class="limit" src="/static/images/order/limit_evaluate_upload.png" @click.stop.prevent="showLimit = false" />
              </view>
            </view>
          </view>
        </view>
        <view v-if="index === (orderListData.length -1 )" class="rate-box">
          <view class="startColumn">
            <view class="rowText">物流服务</view>
            <view class="rowStart">
              <star :disabled="!can_edit" :source.sync="formData" name-key="logisticsScore"></star>
            </view>
          </view>
          <view class="startColumn">
            <view class="rowText">服务态度</view>
            <view class="rowStart">
              <star :disabled="!can_edit" :source.sync="formData" name-key="serviceScore"></star>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view v-if="videoUrl" class="mask-video-box">
      <video :src="videoUrl" class="mask-video" autoplay>
        <cover-image class="close" src="/static/images/icon/icon_return_white.png" @click="videoUrl = ''"></cover-image>
      </video>
    </view>
    <view v-if="allData.can_edit || can_edit" class="bottomSubmit" @click="submitRate('')">{{ isEdit ? (can_edit ? '确认修改' : '编辑修改') :'确认评价' }}</view>
    <base-popup :show="pShow" :show-close="false" pop-style="background-color: transparent" @close="closePopup">
      <view class="upload-popup">
        <view class="select-box">
          <view class="select-item" @click="uploadImage('')">本地图片/拍照</view>
          <view class="select-item" @click="uploadImage('chooseVideo')">本地视频</view>
        </view>
        <view class="select-box">
          <view class="select-item" @click="closePopup">取消</view>
        </view>
      </view>
    </base-popup>
    <confirm-popup ref="confirm">
    </confirm-popup>
  </view>
</template>
<script>
import { mapGetters } from 'vuex'
import confirmPopup from '@/components/confirmPopup/index'
import Star from './components/star'
import { getOrderState } from '@/utils/common'
import './index.scss'
export default {
  name: 'OrderEvalu',
  components: {
    Star,
    confirmPopup
  },
  data() {
    return {
      orderListData: [],
      formData: {
        logisticsScore: 0.1,
        serviceScore: 0.1,
        commentImgList: [],
        commentVideoList: []
      },
      pShow: false,
      showLimit: false,
      selectItem: null,
      allData: {},
      videoUrl: '',
      orderNo: '',
      isEdit: false,
      can_edit: false,
      showResult: false,
      listQuery: {
        page_size: 10,
        page_no: 1,
        loading: false,
        nomore: false
      },
      loading: false
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  async onLoad(options) {
    this.orderNo = options.orderNo
    this.isEdit = options.type === 'edit'
    await this.delWith()
    if (this.isEdit) {
      await this.initEdit()
    } else {
      this.can_edit = true
    }
    this.showResult = true
    if (!uni.getStorageSync('show_evalute_limit' + this.user.mobile)) {
      this.showLimit = true
    }
    setTimeout(() => {
      this.showLimit = false
      uni.setStorageSync('show_evalute_limit' + this.user.mobile, '1')
    }, 1000 * 5)
  },
  methods: {
    // 初始化数据
    initData() {
      this.listQuery.page_no = 1
      this.listQuery.loading = false
      this.listQuery.nomore = false
    },
    closePopup() {
      this.pShow = false
    },
    showPopup(item) {
      this.selectItem = item
      this.pShow = true
    },
    async initEdit() {
      const res = await this.$api.orderApi.orderRatGet({
        order_no: this.orderNo
      })
      if (res.code || !res.data) return
      this.can_edit = res.data.can_edit
      this.formData.serviceScore = res.data.service_score / 10
      this.formData.logisticsScore = res.data.logistics_score / 10
      this.allData = res.data
      res.data.comment_content_modify_v_o_s.map(el => {
        this.orderListData.map(item => {
          if (item.goods_id === el.goods_id) {
            this.formData[item.goods_id] = el.goods_score / 10
            item.commentImgList = el.comment_img ? el.comment_img.split(',') : []
            item.commentVideoList = el.comment_video ? [{
              comment_video: el.comment_video,
              video_cover: el.video_cover
            }] : []
            item.commentContent = el.comment_content || '好评~'
            item.goodsScore = el.goods_score / 10
          }
        })
      })
      console.log('this.formData', this.formData)
    },
    _getOrderState(type) {
      return getOrderState(type)
    },
    showIem(item) {
      console.log(item)
    },
    leftClick() {
      if (this.can_edit) {
        this.$refs.confirm.show({
          content: '退出后编辑过的内容将不保存',
          title: '确认要退出评价?',
          cancleTxt: '取消',
          yesTxt: '确定',
          yesCb: async() => {
            uni.navigateBack()
          },
          cancleCb() {
          }
        })
      } else {
        uni.navigateBack()
      }
    },
    playVideo(video) {
      this.videoUrl = video.comment_video
    },
    async submitRate(confirm) {
      if (!this.can_edit && this.allData.can_edit) {
        this.can_edit = true
        return
      }
      if (this.loading || !this.can_edit) return
      if (this.isEdit && !confirm) {
        this.$refs.confirm.show({
          contentList: ['确认是否提交这次修改', '请慎重考虑，提交后不可修改'],
          title: '温馨提示',
          cancleTxt: '取消',
          yesTxt: '确认',
          yesCb: async() => {
            this.submitRate(true)
          }
        })
        return
      }
      console.log('this.formData', this.formData)
      const data = {
        commentContentRequestList: [],
        commentType: 0, // 评价类型：0-评价 1-追评 2-回复
        orderId: this.orderListData[0].order_id,
        orderNo: this.orderListData[0].order_no,
        serviceScore: this.formData.serviceScore * 10, // 服务评分:10-1星,20-2星,30-3星,40-4星,50-5星
        logisticsScore: this.formData.logisticsScore * 10// 物流评分:10-1星,20-2星,30-3星,40-4星,50-5星

      }
      let isComment = -1
      data.commentContentRequestList = this.orderListData.map((item, index) => {
        if (!item.commentContent) {
          isComment = index
          item.commentContent = '好评~'
        }
        item.goodsScore = this.formData[item.goods_id] * 10
        item.goodsSku = item.goods_skus.reduce((total, el) => total + el.goods_attr, '')
        if (item.commentVideoList && item.commentVideoList.length) {
          item.commentVideo = item.commentVideoList[0].comment_video
          item.videoCover = item.commentVideoList[0].video_cover
        }
        if (item.commentImgList && item.commentImgList.length) {
          item.commentImg = item.commentImgList.join(',')
        }
        item.commentType = 0
        return item
      })
      console.log('data', data, isComment)

      if (this.formData.logisticsScore < 1) {
        this.showToast('物流未评价')
        return
      } else if (this.formData.serviceScore < 1) {
        this.showToast('服务未评价')
        return
      }
      const result = await this.$api.orderApi.orderRateAdd({
        comment_request: JSON.stringify(data)
      })
      if (result.code) {
        this.showToast('提交评价失败', () => {
          this.loading = false
        })
        return
      }
      this.showToast('提交成功,感谢您的评价~', () => {
        this.loading = false
        /* eslint-disable */
          const pages = getCurrentPages()
          /* eslint-disable-end */
          if (pages.length >= 2) {
            if (this.$prePage() && this.$prePage().resetUp) {
              this.$prePage().resetUp()
            }
          }
          setTimeout(() => {
            uni.navigateBack()
          }, 800)
        })
    },
    showToast(msg, cb) {
      uni.showToast({
        title: msg,
        icon: 'none',
        duration: 2000,
        mask: true,
        success: () => {
          setTimeout(() => {
            cb && cb()
          }, 2000)
        }
      })
    },
    async _getDataList() {
      // 1:待付款2:待发货3:待收货4:已收货5:已取消6:付款异常7:超时取消8:已退款
      const result = await this.$api.orderApi.orderRate({
        order_no: this.orderNo,
        page_no: this.listQuery.page_no,
        page_size: this.listQuery.page_size
      })
      return result
    },
    async delWith() {
      const res = await this._getDataList()
      if (res.success) {
        if (this.listQuery.page_no === 1) {
          this.orderListData = []
        }

        res.data.map((item) => {
          item.commentImgList = item.commentImg ? item.commentImg.split(',') : []
          item.commentVideoList = item.commentVideo ? [{
              comment_video: item.comment_video,
              video_cover: item.video_cover
            }] : []
        })

        this.orderListData = this.orderListData.concat(res.data)
        if (res.data.length < this.listQuery.page_size) {
          this.listQuery.nomore = true
        }
        // mescroll.endSuccess(this.listQuery.page_size)
      } else {
        this.orderListData = []
        // mescroll.endErr()
      }
    },
    changeStart(data) {
      this.$set(this.orderListData[data.orderIndex].shopping_items[data.pindex][data.index], 'score', data.i)
    },
    async uploadImage(type) {
      const item = this.selectItem
      const length = 9 - item.commentVideoList.length - item.commentImgList.length
      if (!this.can_edit) return
      if (length < 1) {
        this.showToast('图片最多可上传9张哦~')
        return
      }
      const data = await this.$api.commonApi.uploadImg({ count: length || 1, type, limit: true })
      if (data.success) {
        const newData = data.url.sort((a, b) => {
          return a.sort - b.sort
        })
        newData.map(el => {
          if (el.cover) {
            item.commentVideoList = [{
              comment_video: el.url,
              video_cover: el.cover
            }]
          } else if(el.url){
            item.commentImgList.push(el.url)
          }
        })
      }
      
      this.pShow = false
    },
    delPic(item, index, key) {
      if (!this.can_edit) return
      item[key].splice(index, 1)
    },
    showPreviewImg(img, index, type) {
      let imgList = []
      if (type === 1) {
        img.forEach(item => {
          imgList.push(item.url)
        })
      } else if (type === 2) {
        imgList = img
      }
      uni.previewImage({
        current: index,
        urls: imgList
      })
    }
  }

}
</script>
